package tree;

import commons.TreeNode;

import java.util.*;

/**
 * leet-code(114) 二叉树展开为链表
 *
 * @author Ringo
 * @date 2021/8/14 14:50
 */
public class Flatten {

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));
        System.out.println(list.get(3));
    }

    public static void flatten(TreeNode root) {
        if (root == null) return;
        List<TreeNode> list = preOrder(root);
        for (int i = 0; i < list.size() - 1; i++) {
            list.get(i).left = null;
            list.get(i).right = list.get(i + 1);
        }
        list.get(list.size() - 1).left = null;
    }

    public static List<TreeNode> preOrder(TreeNode root) {
        TreeNode p = root;
        List<TreeNode> list = new LinkedList<>();
        Deque<TreeNode> stack = new LinkedList<>();
        while (p != null || !stack.isEmpty()) {
            if (p != null) {
                list.add(p);
                stack.push(p);
                p = p.left;
            } else {
                p = stack.pop();
                stack.push(p.right);
            }
        }
        return list;
    }
}
